package com.stylefeng.guns.core.util;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JacksonUtil {
	
    private static final Logger LOGGER = LoggerFactory.getLogger(JacksonUtil.class);
	
	public static ObjectMapper objectMapper;
	
	static{
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
//			objectMapper.setSerializationInclusion(Include.NON_EMPTY);
	        // 禁用空对象转换json校验  
			objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);  
			objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		}
	}
	
	public static String toJson(Object object) {

		try {
			return objectMapper.writeValueAsString(object);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(),e);
		}

		return null;
	}
	
	public static <T> T toObject(String string,Class<T> cls){
		if(string == null || string.equals("")){
			return null;
		}
		try {
			return objectMapper.readValue(string, cls);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(),e);
		}
		return null;
		
	}
	
	@SuppressWarnings("unchecked")
	public static <T> List<T> toList(String json, Class<T> beanClass) {  
        try {  
              
            return (List<T>)objectMapper.readValue(json, getCollectionType(List.class, beanClass));  
        } catch (Exception e) {  
        	LOGGER.error(e.getMessage(),e);
        }  
        return null;  
    }

	/**
	 * bean 转 map
	 * @param obj
	 * @return
	 */
	public static  Map<String,Object> beanToMap(Object obj) {
		String str = JacksonUtil.toJson(obj);
		Map<String,Object> result = JacksonUtil.toMap(str, new TypeReference<Map<String, Object>>() {
		});
		return result;
	}

	public static List<String> toList(String json) {  
		return toList(json,String.class);
	}
	
	public static <K,V> Map<K, V> toMap(String src,TypeReference<Map<K, V>> t) {
		if(src != null && !"".equals(src)){
			try {
				Map<K, V> result = objectMapper.readValue(src, t);
				return result;
			} catch (Exception e) {
				LOGGER.error(e.getMessage(),e);
			} 
		}
		return Collections.emptyMap();
	}

	private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {     
	        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);     
	    }   

}
